package com.mall.controller;


import com.mall.entity.ShoppingCart;
import com.mall.pojo.ResponseMessage;
import com.mall.service.IShoppingCartService;
import com.mall.util.UserUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author sppxpp
 * @since 2023-04-15
 */
@RestController
@RequestMapping("/user/shoppingCart")
@CrossOrigin
public class ShoppingCartController {
    final
    IShoppingCartService shoppingCartService;

    public ShoppingCartController(IShoppingCartService shoppingCartService) {
        this.shoppingCartService = shoppingCartService;
    }

    @PostMapping
    public ResponseMessage addItemToShoppingCart(@RequestBody ShoppingCart item, HttpServletRequest request){
        String userId = UserUtils.userId(request);
        if (shoppingCartService.shoppingCartItemIsExist(item.getGoodsId(),userId)){
            return shoppingCartService.addShoppingCartItemCount(item.getGoodsId(),item.getGoodsCount(),userId)
                    ? ResponseMessage.success()
                    : ResponseMessage.custom("-1","添加到购物车失败！");
        }else {
            item.setUserId(userId);
            return shoppingCartService.addShoppingCart(item) ? ResponseMessage.success(item) : ResponseMessage.custom("-1","添加到购物车失败！");
        }
    }

    @GetMapping
    public ResponseMessage queryShoppingCartItems(HttpServletRequest request){
        return ResponseMessage.success(shoppingCartService.queryShoppingCart(UserUtils.userId(request)));
    }

    @PutMapping
    public ResponseMessage updateShoppingCartItem(@RequestBody ShoppingCart item,HttpServletRequest request){
        item.setUserId(UserUtils.userId(request));
        return shoppingCartService.updateShoppingCart(item) ? ResponseMessage.success() : ResponseMessage.custom("-1","修改购物车信息失败！");
    }

    @DeleteMapping
    public ResponseMessage deleteShoppingCartItem(@RequestBody List<String> ids){
        return ResponseMessage.success(shoppingCartService.deleteShoppingCart(ids));
    }
}

